<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="用户ID" prop="priceSum">
        <el-input v-model="queryParams.userId" placeholder="用户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="wordSize">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="服务类型" prop="serviceId">
        <el-select v-model="queryParams.serviceId" placeholder="请选择服务类型">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in managerList"
            :key="index"
            :label="item.typeName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="是否加急" prop="urgent">
        <el-select v-model="queryParams.urgent" placeholder="请选择">
          <el-option
            v-for="(item, index) in urgent"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.editStatus"
          placeholder="请选择订单状态"
        >
          <el-option
            v-for="(item, index) in orderStatus"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务状态" prop="serviceStatus">
        <el-select
          v-model="queryParams.serviceStatus"
          placeholder="请选择服务状态"
        >
          <el-option
            v-for="(item, index) in serviceStatus"
            :key="index"
            :label="item"
            :value="index"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="languageServiceId">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          align="right"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="timestamp"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="服务类型" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.serviceName ||
            (managerJson ? managerJson[scope.row.serviceId].typeName : "")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字数" align="center" prop="wordSize">
        <template slot-scope="scope">
          {{
            [5, 9, 10].includes(scope.row.serviceId) ? "/" : scope.row.wordSize
          }}
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="processMoney" />
      <el-table-column label="目标期刊" align="center" prop="targetJournal">
        <template slot-scope="scope">
          {{
            [5, 6, 7].includes(scope.row.serviceId)
              ? "/"
              : scope.row.targetJournal || "无"
          }}
        </template>
      </el-table-column>
      <el-table-column label="专业领域" align="center" prop="professionalField">
        <template slot-scope="scope">
          {{
            [9, 10].includes(scope.row.serviceId)
              ? "/"
              : scope.row.professionalField
          }}
        </template>
      </el-table-column>
      <el-table-column label="文件数量" align="center">
        <template slot-scope="scope">
          <span class="line underline cursor" @click="showFiles(scope.row)">
            {{ scope.row.manscripts ? scope.row.manscripts.length : 0 }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="订单状态" align="center" width="140px">
        <template slot-scope="scope">
          <el-tag type="success">{{
            orderStatus[scope.row.editStatus]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="服务状态" align="center">
        <template slot-scope="scope">
          {{ serviceStatus[scope.row.serviceStatus] }}
        </template>
      </el-table-column>
      <el-table-column label="需求描述" align="center">
        <template slot-scope="scope">
          <div class="remarks" @click="bzChange(scope.$index, scope.row)">
            {{ scope.row.remarks && scope.row.remarks.slice(0, 15) + (scope.row.remarks.length > 15 ? "..." : "") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="返稿时间" align="center">
        <template slot-scope="scope">
          {{ formatDate(scope.row.returnTime * 1000) }}
        </template>
      </el-table-column>
      <el-table-column label="派稿时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dispatchTime | timestampToDate }} </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="[0, 3].includes(scope.row.editStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="quotation(scope.$index, scope.row)"
            >开始处理</el-button
          >

          <el-button
            v-if="[0, 2, 3, 4].includes(scope.row.editStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="dispatcherProcessd(scope.row, scope.$index)"
            >下载稿件</el-button
          >

          <el-button
            v-if="1 == scope.row.editStatus"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >完工确认</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- <qutation v-if="visible" secondLabel="报价金额" placeholder="请输入报价金额" :visible="visible" editKey="servicePrice"
      @close="closeDialog" @receiveData="receiveData" :qutationData="selectionRow" /> -->

    <manscript
      :manuscript="manuscripts"
      :order="selectRow"
      :visible="filesListVisible"
      :status="false"
      @closeDialog="closeDialogFile"
    />

    <uploadManuscripts
      :id="selectId"
      :visible="ossDialogVisible"
      @close="closeOssDialog"
      @closeOssDialog="closeOssDialog"
      @receiveData="uploadReceiveData"
    />

    <!-- 备注弹窗 -->
    <desc-dialog
      :visible="bzVisible"
      title="需求描述"
      twiceLabel="需求描述"
      :id="bzForm.id"
      :desc="bzForm.content"
      :orderId="bzForm.orderId"
      @cancel="bzVisible = false"
      @confirm="bzVisible = false"
      twiceReadonly
    ></desc-dialog>
  </div>
</template>
<script>
import { listOrder, parseByStart } from "@/api/order/orderByEdit";
import { listManager } from "@/api/service-manager/manager";
import {
  ARRERS,
  ORDERS_MOUDLE_TATUSES,
  EDIT_ORDER_STATUS,
  PRICE_WORD_LABEL,
  SERVICE_STATUS,
} from "@/constant/const";
import { timestampToDate } from "@/utils/time";
import { downloadFile, downloadZip } from '@/utils/dowload';
import { OrderComponentList } from "@/jscomponent/order.component.js";
import { formatDate } from "@/utils/time";
export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      tabName: "all",
      manuscripts: [],
      selectRow: {},
      selectId: 0,
      // 选中数组
      ids: [],
      ossDialogVisible: false,
      filesListVisible: false,
      priceLabel: PRICE_WORD_LABEL,
      urgent: ARRERS,
      orderStatus: EDIT_ORDER_STATUS,
      serviceStatus: SERVICE_STATUS,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      visible: false,
      dispatcherVisible: false, // 派稿弹窗
      selectionRow: {},
      selectionIndex: 0,
      // 弹出层标题
      // 是否显示弹出层
      dateRange: [],
      /**
       * @param {OrderComponentList} orderComponentList
       */
      orderComponentList: undefined,

      // 实例
      instanceName: "getList",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        orderSn: null,
        userName: null,
        userId: null,
        serviceId: null,
        urgent: null,
        editStatus: null,
        parse_time: null,
        serviceStatus: null,
        id: null,
        params: {
          startTime: null,
          endTime: null,
        },
      },
      managerList: [],
      managerJson: {},
      isSearch: false,
      bzVisible: false, // 需求描述弹窗
      bzForm: {
        // 需求描述表单
        id: "",
        content: "",
        orderId: "",
        ind: 0,
      },
    };
  },

  filters: {
    timestampToDate,
  },

  components: {
    qutation: () => import("./component/uploadManuscripts.vue"),
    uploadManuscripts: () => import("./component/uploadManuscripts.vue"),
    manscript: () => import("../order/component/manscript.vue"),
    descDialog: () => import("@/components/descDialog"),
  },

  created() {
    listManager({
      pageNum: 1,
      
    }).then((response) => {
      let managerList = response.rows;

      let json = {};

      for (const iterator of managerList) {
        json[iterator.id] = iterator;
      }
      this.managerJson = json;

      this.managerList = managerList;

      sessionStorage.setItem("managerList", JSON.stringify(this.managerList));
    });
  },

  mounted() {
    // this.orderComponentList = new OrderComponentList(this);
    // console.log(this.$store.state.message.linkEditOrderSnId);
    // if (this.$store.state.message.linkEditOrderSnId) {
    //   this.queryParams.id = this.$store.state.message.linkEditOrderSnId;
    //   this.isSearch = true;
    // }
    this.getList();
  },
  methods: {
    formatDate,

    uploadReceiveData() {
      this.getList();
    },
    dispatcherProcessd(row) {
      let manuscripts = row.manscripts;

      if (null ==manuscripts) {
        return;
      }
      
      downloadZip(manuscripts, row.serviceName +  row.orderSn)

      // for (const iterator of manuscripts) {
      //   setTimeout(()=>{
      //     downloadFile(iterator.file, iterator.originName);
      //   },0)
      // }
    },

    closeDialogFile() {
      this.filesListVisible = false;
    },

    showFiles(row) {
      this.manuscripts = row.manscripts;
      this.selectRow = row;
      console.log("row.manscripts", row.manscripts);
      this.filesListVisible = true;
    },

    receiveAssignData(data) {
      console.log("this.selectionIndex", this.selectionIndex);
      this.orderList[this.selectionIndex].orderStatus = 4;
    },

    // 需求描述
    bzChange(index, row) {
      this.bzForm.id = row.id;
      this.bzForm.orderId = row.orderSn;
      this.bzForm.content = row.remarks;
      this.bzForm.ind = index;
      this.bzVisible = true;
    },

    getList() {
      // let method = OrderComponentList.prototype[this.instanceName];
      // if (!method) {
      //   return;
      // }
      // method.apply(this.orderComponentList);
      let params = {};
      if (this.isSearch) {
        params = Object.assign({}, this.queryParams);
        console.log("params", params);
        if (!this.dateRange.length) {
          delete params.params;
        } else {

          params["params"] = {
            startTime : this.dateRange[0] / 1000,
            endTime : this.dateRange[1] / 1000
          };
        }
      } else {
        params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
        };
      }

      listOrder(params).then((response) => {
        this.orderList = response.rows;

        this.total = response.total;

        this.pageSize = response.pageSize;

        this.loading = false;
        this.$store.commit("SET_ORDER_SNID", null);
      });
    },

    /**
     * 接收子组件数据
     * @param {{}} orderItem
     */
    receiveData(orderItem) {
      console.log(orderItem, this.selectionIndex);
      this.orderList[this.selectionIndex].servicePrice = orderItem.servicePrice;
      this.orderList[this.selectionIndex].serviceStatus = 1;
      this.getList();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /**
     *
     * @param {number} index
     * @param {{}} row
     */
    quotation(index, row) {
      this.$confirm("确认开始处理订单吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((result) => {
          parseByStart(
            {
              id: row.id,
            },
            this
          ).then((result) => {
            this.orderList[index].editStatus = 1;
          });
        })
        .catch((res) => {
          console.log("res", res);
        });
    },

    closeDialog(value) {
      this.visible = value;
    },

    closeDispatcherDialog(value) {
      this.dispatcherVisible = value;
    },

    // 表单重置
    reset() {
      this.queryParams = {
        id: null,
        orderSn: null,
        priceSum: null,
        serviceType: null,
        wordSize: null,
        userId: null,
        targetJournal: null,
        payTime: null,
        overTime: null,
        orderStatus: null,
        editStatus: null,
        commentStatus: null,
        languageServiceId: null,
        payType: null,
        remarks: null,
        status: null,
        translate: null,
        urgent: null,
        platform: null,
        orderType: null,
        couponDeductible: null,
        professionalField: null,
        article: null,
        format: null,
        createTime: null,
        payManagerId: null,
        recommendNumber: null,
        teamId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.isSearch = true;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
      this.resetForm("queryParams");
      this.dateRange = [];
      this.queryParams.pageNum = 1;
      this.isSearch = false;
      this.queryParams.id = null;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.selectId = row.id;

      this.ossDialogVisible = true;
    },

    closeOssDialog(visible) {
      this.ossDialogVisible = visible;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "order/order/export",
        {
          ...this.queryParams,
          ids: this.ids.length ? this.ids : undefined,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
.line {
  margin-left: 20px;
}

.underline {
  text-decoration: underline;
  color: #409eff;
  font-size: 14px;
  text-decoration-color: #409eff;
  margin-left: 11px;
}

.cursor {
  cursor: pointer;
}
.remarks{
  cursor: pointer;
}
</style>
